<template>
  <div class="email-management">
    <el-card class="email-card">
      <template #header>
        <div class="card-header">
          <span>邮箱管理</span>
          <el-button type="primary" @click="handleAdd">
            添加邮箱
          </el-button>
        </div>
      </template>

      <el-table
        :data="emailList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="email" label="邮箱地址" min-width="200" />
        <el-table-column prop="type" label="邮箱类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getEmailTypeTag(row.type)">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUsed" label="最后使用时间" width="180" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.status === 'active' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleTest(row)"
              >
                测试
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="batch-actions" v-if="selectedEmails.length">
        <el-button-group>
          <el-button type="danger" @click="handleBatchDelete">
            批量删除
          </el-button>
          <el-button type="warning" @click="handleBatchTest">
            批量测试
          </el-button>
        </el-button-group>
      </div>
    </el-card>

    <!-- 添加/编辑邮箱对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加邮箱' : '编辑邮箱'"
      width="500px"
    >
      <el-form
        ref="emailFormRef"
        :model="emailForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="邮箱类型" prop="type">
          <el-select v-model="emailForm.type" placeholder="请选择邮箱类型">
            <el-option label="Gmail" value="gmail" />
            <el-option label="Outlook" value="outlook" />
            <el-option label="Yahoo" value="yahoo" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="SMTP服务器" prop="smtp">
          <el-input v-model="emailForm.smtp" placeholder="请输入SMTP服务器地址" />
        </el-form-item>
        <el-form-item label="SMTP端口" prop="port">
          <el-input-number v-model="emailForm.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="密码/令牌" prop="password">
          <el-input
            v-model="emailForm.password"
            type="password"
            placeholder="请输入密码或授权令牌"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const emailFormRef = ref(null)
const selectedEmails = ref([])

// 表单校验规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择邮箱类型', trigger: 'change' }
  ],
  smtp: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码或授权令牌', trigger: 'blur' }
  ]
}

// 邮箱表单
const emailForm = reactive({
  email: '',
  type: '',
  smtp: '',
  port: 587,
  password: ''
})

// 模拟数据
const emailList = ref([
  {
    id: 1,
    email: 'example1@gmail.com',
    type: 'gmail',
    status: 'active',
    lastUsed: '2025-02-22 10:30:00'
  },
  {
    id: 2,
    email: 'example2@outlook.com',
    type: 'outlook',
    status: 'inactive',
    lastUsed: '2025-02-21 15:45:00'
  }
])

// 获取邮箱类型标签样式
const getEmailTypeTag = (type) => {
  const types = {
    gmail: '',
    outlook: 'success',
    yahoo: 'warning',
    other: 'info'
  }
  return types[type] || 'info'
}

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedEmails.value = selection
}

// 添加邮箱
const handleAdd = () => {
  dialogType.value = 'add'
  emailForm.email = ''
  emailForm.type = ''
  emailForm.smtp = ''
  emailForm.port = 587
  emailForm.password = ''
  dialogVisible.value = true
}

// 编辑邮箱
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(emailForm, row)
  dialogVisible.value = true
}

// 测试邮箱
const handleTest = async (row) => {
  try {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success(`邮箱 ${row.email} 测试成功`)
  } catch (error) {
    ElMessage.error(`邮箱 ${row.email} 测试失败`)
  } finally {
    loading.value = false
  }
}

// 删除邮箱
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个邮箱吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    emailList.value = emailList.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    const index = emailList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      emailList.value[index].status = row.status === 'active' ? 'inactive' : 'active'
      ElMessage.success(`${row.status === 'active' ? '禁用' : '启用'}成功`)
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedEmails.value.length) return
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedEmails.value.length} 个邮箱吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const selectedIds = selectedEmails.value.map(row => row.id)
    emailList.value = emailList.value.filter(item => !selectedIds.includes(item.id))
    selectedEmails.value = []
    ElMessage.success('批量删除成功')
  })
}

// 批量测试
const handleBatchTest = async () => {
  if (!selectedEmails.value.length) return

  try {
    loading.value = true
    await Promise.all(selectedEmails.value.map(async (email) => {
      await new Promise(resolve => setTimeout(resolve, 1000))
      return email
    }))
    ElMessage.success(`已完成 ${selectedEmails.value.length} 个邮箱的测试`)
  } catch (error) {
    ElMessage.error('部分邮箱测试失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加新邮箱
        const newEmail = {
          id: Date.now(),
          ...emailForm,
          status: 'active',
          lastUsed: '-'
        }
        emailList.value.push(newEmail)
        ElMessage.success('添加成功')
      } else {
        // 更新现有邮箱
        const index = emailList.value.findIndex(item => item.id === emailForm.id)
        if (index !== -1) {
          emailList.value[index] = { ...emailList.value[index], ...emailForm }
          ElMessage.success('更新成功')
        }
      }
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.email-management {
  padding: 20px;
}

.email-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
